import { CloseOutlined, DeleteOutlined, PaperClipOutlined } from "@ant-design/icons"
import { Button, Card, Input, Form, Select, List } from "antd"
import React, { useCallback, useEffect, useState } from "react"

import { AsyncModal, ModalCustom, ModalRef } from "../modal.context"
import eventBus from "@/utils/event.bus"
import FormUploads from "@/components/form/form.uploads"
import FormEditor from "@/components/form/form.editor"
import "./addTradeInfo.modal.less"
import RelatProductModal from "./relatProduct.modal"
import serviceData from "@/services/service.data"
import checkImage from "@/utils/checkImage.func"
const { Option } = Select
interface Props {
	id: string
}
const AddTradeModal: React.FC<Props & ModalRef> = props => {
	const { modalRef } = props
	const { TextArea } = Input
	const [form] = Form.useForm()
	//!!!!
	let [relateProducts, setRelateProducts] = useState([])
	const closeModal = useCallback(() => {
		modalRef.current.destroy()
	}, [])
	const [tradeClassOne, setTradeClassOne] = useState([])
	const [tradeClassTwo, setTradeClassTwo] = useState([])
	// 初始加载获取一级分类
	useEffect(() => {
		serviceData.getTradeClass({ pid: 0 }).then(res => {
			console.log(res.data)
			setTradeClassOne(res.data)
		})
	}, [])
	// 改变一级分类加载二级分类
	const onValuesChange = useCallback((changedValues: any, values: any) => {
		console.log(changedValues)
		if ("industryId" in changedValues) {
			serviceData.getTradeClass({ pid: changedValues.industryId }).then(res => {
				setTradeClassTwo(res.data)
			})
		}
	}, [])

	const onFinish = useCallback(
		data => {
			const productIds: any[] = []
			relateProducts.forEach(item => {
				productIds.push(item.id)
			})
			console.log(data)
			if (!props.id) {
				serviceData
					.addTradeData({
						industryId: data.industryId,
						solutionId: data.solutionId,
						title: data.title,
						content: data.content,
						products: productIds,
						image: data.image[0]?.fileSaveUrl,
						introduction: data.introduction
					})
					.then(res => {
						if (res.code === 200) {
							console.log(res)
							eventBus.emit("doTradeInfo")
							closeModal()
						}
					})
			} else {
				// serviceData
				// 	.updateTradeData({
				// 		id: props.id,
				// 		industryId: 998,
				// 		solutionId: 120,
				// 		title: "tjci5m",
				// 		content: "wjxs2g",
				// 		products: [257]
				// 	})
				// 	.then(res => {
				// 		if (res.code === 200) {
				// 			eventBus.emit("doSceneTemplate")
				// 			closeModal()
				// 		}
				// 	})
			}
		},
		[relateProducts]
	)

	useEffect(() => {
		eventBus.on("RelateProducts", val => {
			setRelateProducts(val)
		})
		return () => {
			eventBus.off("RelateProducts")
		}
	}, [])
	const relatProductsBtn = () => async () => {
		const modalData = await AsyncModal({
			content: RelatProductModal,
			mask: true
		})
		setRelateProducts(modalData)
	}
	const deleterelateProduct = (id: number) => () => {
		setRelateProducts(
			relateProducts.filter(item => {
				return item.id !== id
			})
		)
	}
	return (
		<Card
			id="tradeInfoBox"
			style={{ width: 700 }}
			title={props.id == "" ? "新增行业信息" : "编辑行业信息"}
			extra={
				<Button type="text" onClick={closeModal}>
					<CloseOutlined />
				</Button>
			}
		>
			<div className="productInfo">
				<div className="productInfoForm">
					<Form
						layout="horizontal"
						labelCol={{ span: 6 }}
						// wrapperCol={{ span: 19 }}
						form={form}
						preserve={false}
						onFinish={onFinish}
						onValuesChange={onValuesChange}
					>
						<Form.Item label="行业：" name="industryId" rules={[{ required: true, message: "请选择行业分类" }]}>
							<Select placeholder={"行业分类"}>
								{tradeClassOne.map(item => (
									<Option key={item.id} value={item.id}>
										{item.title}
									</Option>
								))}
							</Select>
						</Form.Item>
						<Form.Item label="应用场景" name="solutionId" rules={[{ required: true, message: "请选择应用场景" }]}>
							<Select placeholder={"请选择应用场景"}>
								{tradeClassTwo.map(item => (
									<Option key={item.id} value={item.id}>
										{item.title}
									</Option>
								))}
							</Select>
						</Form.Item>
						<Form.Item label="解决方案名称" name="title" rules={[{ required: true, message: "请输入解决方案名称" }]}>
							<Input placeholder="请输入解决方案名称" />
						</Form.Item>
						<Form.Item
							label="封面图："
							name="image"
							rules={[{ required: true, message: "请选择封面图" }]}
							extra="文件大小2M之内，分辨率796*448jpg、png"
						>
							<FormUploads
								accept=".png, .jpg, .jpeg"
								customCheck={checkImage("image", 2)}
								checkType={"hotImage"}
								imgAction={{ crop: true, aspectRatio: [796, 448] }}
							></FormUploads>
						</Form.Item>
						<Form.Item label="方案简介：" name="introduction">
							<TextArea showCount maxLength={150} />
						</Form.Item>
						<Form.Item label="具体内容：" name="content">
							<FormEditor
								onChange={e => {
									console.log(e)
								}}
							/>
						</Form.Item>
						<Form.Item label="关联产品：">
							<Button onClick={relatProductsBtn()}>{"+添加"}</Button>
							{!!relateProducts && (
								<List
									grid={{ gutter: 16, column: 2 }}
									dataSource={relateProducts}
									renderItem={item => (
										<List.Item>
											<div style={{ margin: "10px 0" }}>
												<PaperClipOutlined style={{ marginRight: "5px" }} />
												<span>{item.title}</span>
												<DeleteOutlined style={{ marginLeft: "10px" }} onClick={deleterelateProduct(item.id)} />
											</div>
										</List.Item>
									)}
								/>
							)}
						</Form.Item>

						<Form.Item style={{ textAlign: "right" }}>
							<Button type="primary" htmlType="submit">
								保存
							</Button>
							<Button style={{ marginLeft: 10 }} htmlType="button" onClick={closeModal}>
								取消
							</Button>
						</Form.Item>
					</Form>
				</div>
			</div>
		</Card>
	)
}

export default AddTradeModal
